'use strict';

angular.module('Common').controller('ScheduleRequestListController', ['$scope', 'CommonEnum', 'BaseModule', 'BaseFunction', '$location', 'Authentication',
    function($scope, CommonEnum, BaseModule, BaseFunction, $location, Authentication) {
        $scope.ScheduleStatusEnum = BaseFunction.getEnum('CommonEnum.ScheduleStatus');
    	BaseModule.initModule($scope, 'ScheduleRequest');
        $scope.Module.ScheduleRequest.Populate = [{path: 'Scheduler', select: 'Code Name'}, {path: 'ScheduleProgram', select: 'Code Name'}];
        $scope.Module.ScheduleRequest.PageSize = 15;

        $scope.btnAdd = function(){
        	$location.url('/index/ScheduleRequest/Edit');
        };

        $scope.rowDblClick = function(){
        	$scope.$apply(function(){
                $location.url("/index/ScheduleRequest/Edit/" + $scope.Module.ScheduleRequest.FocusedRecord._id);
            });
        };

        $scope.btnDelete = function(){
            var selectedRecords = $scope.Module.ScheduleRequest.SelectedRecords;
            for(var i=0; i<selectedRecords.length; i++){
                if(selectedRecords[i].Status == CommonEnum.ScheduleStatus.Wait.Value || 
                    selectedRecords[i].Status == CommonEnum.ScheduleStatus.Execution.Value){
                    BaseFunction.alert('状态为等待中或者是执行中的不能被删除', '删除错误提示');
                    return;
                }
            }
        	$scope.Module.ScheduleRequest.deleteSelecteds();
        };

        $scope.btnSubmitRequest = function(){
            var recordIds = [];
            var selectedRecords = $scope.Module.ScheduleRequest.SelectedRecords;
            selectedRecords.forEach(function(record){
                if(record.Status == $scope.ScheduleStatusEnum.No.Value){
                    recordIds.push(record._id);
                }
            });

            if(recordIds.length > 0){
                BaseFunction.request('/api/Common/submitRequests', false, {ScheduleRequestIds: recordIds}, 
                    function(records){
                        $scope.Module.ScheduleRequest.load();
                });
            }
        };

        $scope.btnCancelRequest = function(){
            var recordIds = [];
            var selectedRecords = $scope.Module.ScheduleRequest.SelectedRecords;
            selectedRecords.forEach(function(record){
                if(record.Status == $scope.ScheduleStatusEnum.Wait.Value || record.Status == $scope.ScheduleStatusEnum.Execution.Value){
                    recordIds.push(record._id);
                }
            });

            if(recordIds.length > 0){
                BaseFunction.request('/api/Common/cancelRequests', false, {CancelRequestIds: recordIds}, 
                    function(records){
                        $scope.Module.ScheduleRequest.load();
                });               
            }
        };
    }
]);
